﻿using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;


namespace BestTrader.Cms.Core.Extensions
{
    public static class HttpContextExtensions
    {
        /// <summary>
        /// 获取客户Ip
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static string GetClientUserIp(this HttpContext context)
        {
            var ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
            if (string.IsNullOrEmpty(ip))
            {
                ip = context.Connection.RemoteIpAddress.ToString();
            }
            return ip;
        }

        ///// <summary>
        ///// 取机器名DNS 
        ///// </summary>
        //public static string GetHostName(this HttpContext context) {
        //    var host = Dns.GetHostName();
        //    return host;
        //}

        //public static string GetMac(this HttpContext context)
        //{
        //    string mac = "";
        //    string clientip = "";
        //    System.Diagnostics.Process process = new System.Diagnostics.Process();
        //    process.StartInfo.FileName = "ipconfig";
        //    //process.StartInfo.Arguments = "-a " + clientip;
        //    process.StartInfo.UseShellExecute = false;
        //    process.StartInfo.CreateNoWindow = true;
        //    process.StartInfo.RedirectStandardOutput = true;
        //    process.Start();
        //    string ipOutput = process.StandardOutput.ReadToEnd();
        //    int ipLength = ipOutput.IndexOf("IPv4 Address . . . . . . . . . . . . : ");
        //    if (ipLength > 0)
        //    {
        //        clientip = ipOutput.Substring(ipLength + 39, 15).Replace("\r\n", "").Trim();
        //    }
        //    if (ipLength == -1)
        //    {
        //        ipLength = ipOutput.IndexOf("IPv4 地址 . . . . . . . . . . . . : ");
        //        if (ipLength > 0)
        //        {
        //            clientip = ipOutput.Substring(ipLength + 34, 15).Replace("\r\n", "").Trim();
        //        }
        //    }
        //    if (!clientip.IsNullOrWhiteSpace())
        //    {
        //        process.StartInfo.FileName = "nbtstat";
        //        process.StartInfo.Arguments = "-a " + clientip;
        //        process.StartInfo.UseShellExecute = false;
        //        process.StartInfo.CreateNoWindow = true;
        //        process.StartInfo.RedirectStandardOutput = true;
        //        process.Start();
        //        string output = process.StandardOutput.ReadToEnd();
        //        int length = output.IndexOf("MAC Address =");
        //        if (length > 0)
        //        {
        //            mac = output.Substring(length + 14, 17);
        //        }
        //        if (length == -1)
        //        {
        //            length = output.IndexOf("MAC 地址 =");
        //            if (length > 0)
        //            {
        //                mac = output.Substring(length + 9, 17);
        //            }
        //        }
        //    }
        //    return mac;
        //}

        //public static List<string> GetActiveMacAddress(this HttpContext context, string separator = "-")
        //{
        //    var macAddress = new List<string>();
        //    NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
        //    //Debug.WriteLine("Interface information for {0}.{1}  ",
        //    // computerProperties.HostName, computerProperties.DomainName);
        //    if (nics == null || nics.Length < 1)
        //    {
        //        //Debug.WriteLine(" No network interfaces found.");
        //        return macAddress;
        //    }
        //    //Debug.WriteLine(" Number of interfaces .................... : {0}", nics.Length);
        //    foreach (NetworkInterface adapter in nics.Where(c =>
        //     c.NetworkInterfaceType != NetworkInterfaceType.Loopback && c.OperationalStatus == OperationalStatus.Up))
        //    {
        //        //Debug.WriteLine("");
        //        //Debug.WriteLine(adapter.Name + "," + adapter.Description);
        //        //Debug.WriteLine(string.Empty.PadLeft(adapter.Description.Length, '='));
        //        //Debug.WriteLine(" Interface type .......................... : {0}", adapter.NetworkInterfaceType);
        //        //Debug.Write(" Physical address ........................ : ");
        //        //PhysicalAddress address = adapter.GetPhysicalAddress();
        //        //byte[] bytes = address.GetAddressBytes();
        //        //for (int i = 0; i < bytes.Length; i++)
        //        //{
        //        // // Display the physical address in hexadecimal.
        //        // Debug.Write($"{bytes[i]:X2}");
        //        // // Insert a hyphen after each byte, unless we are at the end of the 
        //        // // address.
        //        // if (i != bytes.Length - 1)
        //        // {
        //        //  Debug.Write("-");
        //        // }
        //        //}

        //        //Debug.WriteLine("");

        //        //Debug.WriteLine(address.ToString());

        //        IPInterfaceProperties properties = adapter.GetIPProperties();

        //        var unicastAddresses = properties.UnicastAddresses;
        //        if (unicastAddresses.Any(temp => temp.Address.AddressFamily == AddressFamily.InterNetwork))
        //        {
        //            var address = adapter.GetPhysicalAddress();
        //            if (string.IsNullOrEmpty(separator))
        //            {
        //                macAddress.Add(address.ToString());
        //            }
        //            else
        //            {
        //                macAddress.Add(string.Join(separator, address.GetAddressBytes()));
        //            }
        //        }
        //    }

        //    return macAddress;
        //}

        /// <summary>
        /// 判断是否ajax请求
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static bool IsAjaxRequest(this HttpRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            return request.Headers.ContainsKey("X-Requested-With") &&
                   request.Headers["X-Requested-With"].Equals("XMLHttpRequest");
        }
    }
}
